package syn;
/**
不安全的买票
 线程不安全，有负数
 */
public class UnsafeBuyTicket {
    public static void main(String[] args) {
        BuyTicket station = new BuyTicket();

        new Thread(station,"小王").start();
        new Thread(station,"小张").start();
        new Thread(station,"黄牛党").start();
    }
}

class BuyTicket implements Runnable{
    private int ticketNums = 10;
    private boolean flag = true;
    @Override
    public void run() {
        //买票
        while(flag){
            buy();
        }
    }
    public synchronized void buy(){
        //判断是否有票
        if(ticketNums <= 0){
            flag = false;
            return;
        }
        try {
            Thread.sleep(200);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(Thread.currentThread().getName()+"买到第"+ticketNums--+"张票");
    }
}